package com.xy.aspect;

import com.xy.annotation.TimeCost;
import com.xy.annotation.WebLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
//@Profile({"dev", "test"})
@Slf4j
public class TimeCostAspect {

    @Pointcut("@annotation(com.xy.annotation.TimeCost)")
    public void timeCost(){};

    @Around("timeCost()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String description = getAspectLogDescription(joinPoint);
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        log.info("{},耗时：{}", description, System.currentTimeMillis() - start);
        return result;
    }

    private String getAspectLogDescription(JoinPoint joinPoint) throws ClassNotFoundException {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Class<?> aClass = Class.forName(targetName);
        Method[] methods = aClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == args.length) {
                    description.append(method.getAnnotation(TimeCost.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }
}
